﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using NationalD3.Domain.Entities;
using NationalD3.Infrastructure.Data.Mappings;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
using System.IO;

namespace NationalD3.Infrastructure.Data.Context
{
    /// <summary>
    /// 上下文类
    /// </summary>
    public class StudentContext : DbContext
    {
        /// <summary>
        /// 重写基类的方法 用于模型创建
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration(new StudentMap()); //应用FluentApi映射配置对象
        }

        /// <summary>
        /// 重写基类的方法 用于数据库选项配置
        /// </summary>
        /// <param name="optionsBuilder"></param>
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //从配置文件读取连接字符串
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
            //判断是什么数据库
            if (config.GetSection("DbType").Value.Equals("MySql"))
            {
                var strConn = config.GetConnectionString("MySqlConnection");
                optionsBuilder.UseMySql(strConn, ServerVersion.AutoDetect(strConn));
            }
            else
            {
                var strConn = config.GetConnectionString("DefaultConnection");
                optionsBuilder.UseSqlServer(strConn); //使用sqlserver数据库
            }
           
        }

        public DbSet<Student>  Students { get; set; }
    }
}
